﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Elentok.Common.Wpf.Helpers
{
  /// <summary>
  /// Adds the "BoundPassword" attached property for the <see cref="PasswordBox"/> control
  /// </summary>
  public static class PasswordBoxHelper
  {
    /// <summary>
    /// The "BoundPassword" attached property allows binding the "Password" property
    /// of a "PropertyBox" control
    /// </summary>
    public static readonly DependencyProperty BoundPassword =
      DependencyProperty.RegisterAttached(
        "BoundPassword",
        typeof(string),
        typeof(PasswordBoxHelper),
        new FrameworkPropertyMetadata(string.Empty, OnBoundPasswordChanged));

    private static void OnBoundPasswordChanged(DependencyObject obj,
      DependencyPropertyChangedEventArgs eventArgs)
    {
      PasswordBox box = (PasswordBox)obj;

      // avoid recursive updating by ignoring the box's changed event
      box.PasswordChanged -= new RoutedEventHandler(box_PasswordChanged);

      string newValue = (string)eventArgs.NewValue;
      if (string.Compare(box.Password, newValue) != 0)
      {
        box.Password = newValue;
      }

      box.PasswordChanged += new RoutedEventHandler(box_PasswordChanged);
      
    }

    private static void box_PasswordChanged(object sender, RoutedEventArgs e)
    {
      PasswordBox box = (PasswordBox)sender;
      box.SetValue(BoundPassword, box.Password);
    }

    /// <summary>
    /// Sets the "BoundPassword" property
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="value"></param>
    public static void SetBoundPassword(DependencyObject obj, string value)
    {
      obj.SetValue(BoundPassword, value);
    }

    /// <summary>
    /// Gets the value of the "BoundPassword" property
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string GetBoundPassword(DependencyObject obj)
    {
      return (string)obj.GetValue(BoundPassword);
    }
  }
}
